package cn.harry.cabinet.view.adapter

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import cn.harry.cabinet.R
import cn.harry.cabinet.model.ui.CardRecordUI

/**
 * 刷卡记录适配器
 */
class CardRecordAdapter(
    private val context: Context,
    private val records: MutableList<CardRecordUI>
) : RecyclerView.Adapter<CardRecordAdapter.CardRecordViewHolder>() {

    inner class CardRecordViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvCardNumber: TextView = itemView.findViewById(R.id.tvCardNumber)
        val tvCardType: TextView = itemView.findViewById(R.id.tvCardType)
        val tvTime: TextView = itemView.findViewById(R.id.tvTime)
        val btnCopy: ImageButton = itemView.findViewById(R.id.btnCopy)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardRecordViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_card_record, parent, false)
        return CardRecordViewHolder(view)
    }

    override fun onBindViewHolder(holder: CardRecordViewHolder, position: Int) {
        val record = records[position]
        
        holder.tvCardNumber.text = record.cardId
        holder.tvCardType.text = record.cardType.name
        holder.tvTime.text = record.timeStr
        
        // 复制卡号功能
        holder.btnCopy.setOnClickListener {
            copyToClipboard(record.cardId)
        }
        
        // 点击整个item也可以复制
        holder.itemView.setOnClickListener {
            copyToClipboard(record.cardId)
        }
    }

    override fun getItemCount(): Int = records.size

    /**
     * 添加新记录到列表顶部
     */
    fun addRecord(record: CardRecordUI) {
        records.add(0, record)
        notifyItemInserted(0)
    }

    /**
     * 清空所有记录
     */
    fun clearRecords() {
        val size = records.size
        records.clear()
        notifyItemRangeRemoved(0, size)
    }

    /**
     * 复制到剪贴板
     */
    private fun copyToClipboard(text: String) {
        val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        val clip = ClipData.newPlainText("卡号", text)
        clipboard.setPrimaryClip(clip)
        Toast.makeText(context, "卡号已复制: $text", Toast.LENGTH_SHORT).show()
    }
}
